import { loginAPI, getUserProfileAPI, getUserInfoAPI } from "@/api/user";
import { resetRouter } from "@/router";
import { getToken, removeToken, setToken } from "@/utils/auth";

const state = () => {
  return {
    // 用户令牌
    token: getToken() || "",
    // 用户信息
    userInfo: {},
  };
};

const mutations = {
  //设置token
  setToken: (state, token) => {
    state.token = token;
    //本地存一份token
    setToken(token);
  },
  // 设置用户信息
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  // 清空token
  removeToken: (state) => {
    state.token = "";
    //清空本地token
    removeToken("");
  },
  // 清空用户信息
  removeUserInfo: (state) => {
    state.userInfo = {};
  },
};

const actions = {
  // 登入action
  loginAction: async ({ commit }, loginForm) => {
    // 发登入请求
    const resp = await loginAPI(loginForm);
    //提交mutation
    commit("setToken", resp.data);
  },
  // 获取用户信息action
  getUserInfoAction: async ({ commit }) => {
    //掉接口发请求
    const { data: UserProfile } = await getUserProfileAPI();
    // 基于此次接口返回的userId发出第二次请求（获取用户头像信息）
    const { data: userInfo } = await getUserInfoAPI(UserProfile.userId);
    //提交mutation
    //{...UserProfile,...userInfo}两个对象合并之后作为参数传给mutation函数
    commit("setUserInfo", { ...UserProfile, ...userInfo });
  },
  // 退出登入action
  logouAction: ({ commit }) => {
    commit("removeToken");
    commit("removeUserInfo");
    // 重置路由实例（吧路由表中的所有信息删除）
    resetRouter();
    //清空vuex中的路由
    commit("route/removeRoutes", null, {
      root: true,
    });
    // 重置主题色
    commit("settings/resetTheme", null, {
      root: true,
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
